local gongtu = fk.CreateSkill{
  name = "investiture__gongtu",
}

Fk:loadTranslationTable{
  ["investiture__gongtu"] = "巩土",
  [":investiture__gongtu"] = "一名角色的结束阶段，你可以令其获得至多两张本回合不因使用进入弃牌堆的牌，然后若其本回合造成过伤害，你需将两张牌置于牌堆顶或失去1点体力。",

  ["#investiture__gongtu"] = "巩土：可以令 %dest 获得至多两张本回合不因使用进入弃牌堆的牌（不选则不会发动）",
  ["#investiture__gongtu-put"] = "巩土：将两张牌置于牌堆顶，否则失去1点体力",

  ["$investiture__gongtu"] = "人总有一死，我商容死不足惜，只望我的苦口良言能令君觉醒，死亦足矣。",
}

-- center cards
---@param room Room
---@param id integer
---@return boolean
local filter = function (id, room)
  local end_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
  if not end_event then return false end
  local events = room.logic.event_recorder[GameEvent.MoveCards]

  for i = #events, 1, -1 do
    local e = events[i] ---@type GameEvent.MoveCards
    if e.id <= end_event.id then break end

    for _, move in ipairs(e.data) do
      if move.toArea == Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          if info.cardId == id then
            return move.moveReason ~= fk.ReasonUse
          end
        end
      end
    end
  end

  return false
end

--- caused damage during this turn?
---@param room Room
---@param player ServerPlayer
---@return boolean
local caused = function (room, player)
  local func = function (e) return e.data.from == player end
  local e = room.logic:getActualDamageEvents(1, func, Player.HistoryTurn)
  return #e == 1
end

-- main effect
gongtu:addEffect(fk.EventPhaseStart, {
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(gongtu.name) and target.phase == Player.Finish
  end,
  on_cost = function (self, event, target, player, data)
    local cards = {}
    for _, id in ipairs(player.room.discard_pile) do
      if filter(id, player.room) then
        table.insert(cards, id)
      end
    end

    local card_data = {{"pile_discard", cards}}
    local choosed = player.room:askToChooseCards(player, {
      target = player,
      min = 0,
      max = 2,
      flag = { card_data = card_data },
      skill_name = gongtu.name,
      prompt = "#investiture__gongtu::"..target.id,
    })

    if choosed and #choosed > 0 then
      event:setCostData(self, choosed)
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cards = event:getCostData(self) ---@type integer[]
    room:obtainCard(target, cards, true, fk.ReasonJustMove, player, gongtu.name)

    if player.dead or not caused(room, target) then return end
    local put = room:askToCards(player, {
      min_num = 2,
      max_num = 2,
      skill_name = gongtu.name,
      prompt = "#investiture__gongtu-put",
      include_equip = true,
      cancelable = true,
    })

    if #put > 0 then
      room:moveCardTo(put, Card.DrawPile, nil, fk.ReasonPut, gongtu.name, nil, false, player)
    else
      player.room:loseHp(player, 1, gongtu.name)
    end
  end
})

return gongtu